package _15_generics._15_8.exercise;

import java.util.HashMap;
import java.util.Map;

import static net.mindview.util.Print.print;

/**
 * Modify ClassTypeCapture.java by adding a
 * Map<String,Class<?>>, a method
 * addType(String typename, Class<?> kind), and a
 * method createNew(String typename).createNew()
 * will either produce a new instance of the class
 * associated with its arguments string,or produce
 * an error message
 */
public class E21_ClassTypeCapture2 {
}

class ClassTypeCapture2{
    Map<String,Class<?>> types = new HashMap<>();

    void addType(String typename, Class<?> kind){
        types.put(typename,kind);
    }

    Object createNew(String typename){
        Class<?> cl = types.get(typename);
        try {
            return cl.newInstance();
        } catch(NullPointerException e) {
            print("Not a registered typename: " + typename);
        } catch(Exception e) {
            print(e.toString());
        }
        return null;
    }
}
